<?php
class Loto_Controller_Plugin_Acl extends Zend_Controller_Plugin_Abstract 
{
    public function preDispatch(Zend_Controller_Request_Abstract $request){
        $DbTableRule = new Application_Model_DbTable_Rules();
        $RuleRowSet = $DbTableRule->fetchDataPermission();
        
        // Load roles
        $DbTableGroup = new Application_Model_DbTable_Groups();
        $RoleRowSet = $DbTableGroup->fetchAll();        
        
        // Load resources
        $DbTableController = new Application_Model_DbTable_Controllers();
        $ControllerRowSet = $DbTableController->fetchAll();
        // Set Zend_Acl
        $acl = new Zend_Acl();
        
        $acl->addRole(new Zend_Acl_Role("guest"));
        // Add Roles
        foreach($RoleRowSet as $group) {
            $acl->addRole(new Zend_Acl_Role($group->GroupsName));
        }
        
        // Add Resources
        foreach($ControllerRowSet as $control) {
            $acl->add(new Zend_Acl_Resource($control->ControllersName));
        }

        foreach($RuleRowSet as $row) {            
            // set permission
            if($row->allow) {
                $acl->allow($row->group, $row->controller, array($row->action));
            }else{
                $acl->deny($row->group, $row->controller, array($row->action));
            }            
        }
        
        $auth = Zend_Auth::getInstance();
        if($auth->hasIdentity()) {
            $identity = $auth->getIdentity();
            $row = $DbTableGroup->find($identity->Groups)->current();
            $role = $row->GroupsName;
        }else{
            $role = "guest";
        }
        
        $controller = $request->controller;
        $action = $request->action;
        
        if(!$acl->isAllowed($role, $controller, $action)) {
            if($role == "guest") {
                $request->setControllerName("user");
                $request->setActionName("login");
            }else{
                $request->setControllerName("error");
                $request->setActionName("noauth");
            }
        }
    }   
}
?>